package model

import (
	"fmt"
	"github.com/go-xorm/xorm"
	"protobuf/trade"
	"time"
)

const (
	Zero = iota
)

/**
新增一条交易内容
*/
func AddTrade(request *trade.TradeRequest) error {
	var t Trade

	t.Uid = request.GetUid()
	t.Price = request.GetPrice()
	t.Type = request.GetType()
	t.TotalNum = request.GetTotalNum()
	t.Status = trade.TradeRequest_HANDLING
	t.LeftNum = request.GetTotalNum()
	t.DealNum = Zero
	t.Updated = time.Now().Unix()

	e := GetEngine()
	id, err := e.Insert(&t)
	if err != nil {
		return err
	}
	request.Id = id
	return nil
}

func GetOneBuy(t *Trade) (bool, error) {
	e := GetEngine()
	has, err := e.Where("type = ?", trade.TradeRequest_BUY).And("status = ?", trade.TradeRequest_HANDLING).Desc("price").Asc("id").Get(t)
	return has, err

}

func GetAllSell(t *Trade) (bool, error) {
	e := GetEngine()
	has, err := e.Where("type = ?", trade.TradeRequest_SELL).And("status = ?", trade.TradeRequest_HANDLING).Asc("price").Asc("id").Get(t)
	return has, err
}

func SaveTrade(t *Trade) (int64, error) {
	e := GetEngine()
	return e.ID(t.Id).Update(t)
}

// 查询交易列表
func GetTradeList(uid int64, index int64, size int64, t trade.TradeRequest_Type, status trade.TradeRequest_Status) ([]*Trade, error) {
	e := GetEngine()
	var session *xorm.Session = e.NewSession()
	defer session.Close()
	fmt.Print(uid, index, size, t, status)

	if t != trade.TradeRequest_ALL {
		session = session.Where("type = ?", t)
	}
	if status != trade.TradeRequest_OLL {
		session = session.Where("status = ?", status)
	}
	if uid != 0 {
		session = session.Where("uid = ?", uid)
	}
	if size != 0 {
		size = 10
	}
	r := make([]*Trade, 0)
	err := session.Desc("id").Limit(int(index), int(size*index)).Find(&r)
	if err != nil {
		return nil, err
	}
	return r, nil
}

// 取消交易
func CancelTrade(uid int64, id int64) bool {
	session := GetEngine().NewSession()
	defer session.Close()
	var t = new(Trade)
	has, err := session.Where("uid = ?", uid).Where("id = ?", id).Get(t)
	if !has {
		return false
	}
	if err != nil {
		return false
	}
	t.Status = trade.TradeRequest_CANCEL
	_, err = session.ID(t.Id).Cols("status").Update(t)
	if err != nil {
		return false
	}
	return true
}

// 获取系统日志 .
func GetSystemLog(index int64, size int64, t trade.TradeRequest_Type) ([]*TradeLog, error) {
	session := GetEngine().NewSession()
	defer session.Close()
	l := make([]*TradeLog, 0)
	if index <= 0 {
		index = 0
	}
	if size == 0 {
		size = 10
	}
	if t != trade.TradeRequest_ALL {
		session = session.Where("type = ?", t)
	}
	err := session.Limit(int(index), int(index*size)).Find(&l)
	if err != nil {
		return nil, err
	}
	return l, nil
}

func UpdateResult(rs *Result) {
	session := GetEngine().NewSession()
	defer session.Close()
	session.ID(rs.Id).Cols("status").Update(rs)
}
